package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.*;
import com.lidroid.xutils.ViewUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.sso.UMSsoHandler;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.LinkProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.view.CircleImageView;
import so.shanku.essential.view.ListViewNoScroll;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/9/8 0008.
 * 发现详情
 */
public class ArticalDetailActivity extends BaseUIActivity {

    /**
     * 加载内容的控件
     */
    @ViewInject(id = R.id.content_layout)
    private LinearLayout content_layout;

    private LinearLayout head_layout;//头部布局

    /**
     * 品牌logo
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.find_contents_wb)
    private WebView find_contents_wb;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.myProgressBar)
    private ProgressBar myProgressBar;



    /**
     * 相关用户的title
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.relation_person_layout)
    private LinearLayout relation_person_layout;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.relation_person_info)
    private LinearLayout relation_person_info;


    /**
     * 相关商品的title
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.relation_goods)
    private LinearLayout relation_goods_title_layout;


    //相关商品
    @ViewInject(id = R.id.noscroll_gv)
    private ListViewNoScroll relation_goods_xgv;
    private LinkProductAdapter relationProductAdapter;


    private String discoredId;//发现id

    private JsonMap goodsDetailDatas;//商品强请
    private int nPage = 0;
    /**
     * 商品的信息数据
     */
    private List<JsonMap<String, Object>> goodsDatas;

    private JsonMap findDatas;
    private ArrayList<JsonMap<String, Object>> relationPersons = new ArrayList<JsonMap<String, Object>>();
    private boolean isCollected;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.artical_detail_layout);
        setCenter_title(R.string.find);
        setBtn_menu(R.drawable.comments_msg, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msg_iv_click(v);
            }
        }, R.drawable.more_white, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               more_iv_click(v);
            }
        });
        head_layout = (LinearLayout) getLayoutInflater().inflate(R.layout.artical_detail_head_layout, null);
        ViewUtils.inject(this, head_layout);
        content_layout.addView(head_layout, 0);

        discoredId = getIntent().getStringExtra(Constant.ID);

        relationProductAdapter = new LinkProductAdapter(this);
        relation_goods_xgv.setOnItemClickListener(onItemClickListener);

        String formartStr = GetDataConfing.Url_Base + "FindBrand/AppFindBrandDetai?userId=%s&disId=%s";
        String url = String.format(formartStr, Utils.getUserId(mContext), discoredId);
        setWebViewFeature();
        find_contents_wb.loadUrl(url);

        getArticalDetail();
        //getRelationGoods();
    }


    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position >= 0) {
                int goodsType = goodsDatas.get(position).getInt("productType");
                goodsType = 0;
                if (goodsType == 0) {
                    String goodsId = goodsDatas.get(position).getStringNoNull("productID");
                    seeProductDetail(goodsId);
                } else {
                    Intent intent = new Intent(mContext, UrlWebviewActivity.class);
                    intent.putExtra(ExtraKeys.Key_Msg1, 8);
                    intent.putExtra(ExtraKeys.Key_Msg2, goodsDatas.get(position).getStringNoNull("productUrl"));
                    jumpTo(intent);
                }
            }
        }
    };


    /**
     * 获取相关商品  {DiscoverId:3, currentPage:1,pageSize:10}
     */
    private void getRelationGoods() {

        Map<String, Object> params = new HashMap<String, Object>();

        params.put("page", nPage + 1);
        params.put("articleID", discoredId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetArticalRelationGoods);
        queue.setWhat(GetDataConfing.What_GetArticalRelationGoods);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        getDataUtil.getData(queue);
    }


    /**
     * {DiscoverId:3}
     * ProudctWebService.asmx/GetDiscoverDetails   {userID: 2,  articleID: 18}
     * 获取商品详情
     */
    private void getArticalDetail() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();

        if (Utils.isHasLogin(this)) {
            params.put("userID", Utils.getUserId(mContext));
        }
        params.put("articleID", discoredId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetArticalDetail);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetArticalDetail);
        getDataUtil.getData(queue);
    }

    /**
     * 校验数据 显示无数据等
     * <p/>
     * 是否请求正常 网络错误且数据为空的话显示网络异常界面 提供刷新的接口
     *
     * @param data_server
     */
    private void validateData(List<JsonMap<String, Object>> data_server) {
        relation_goods_xgv.requestLayout();
        find_contents_wb.requestLayout();
//        if (data_server.size() == 0 || data_server.size() % pageSize != 0) {
//            relation_goods_xgv.setPullLoadEnable(false);
//        } else {
//            relation_goods_xgv.setPullLoadEnable(true);
//        }
    }

    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetArticalRelationGoods) {
                        List<JsonMap<String, Object>> data_server = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setData(data_server);
                        //validateData(data_server);
                    } else if (entity.what == GetDataConfing.What_GetArticalDetail) {
                        goodsDetailDatas = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        refreshGoodsDetail(goodsDetailDatas);
                    } else if (entity.what == GetDataConfing.What_CollectionArtical) { //点赞
                        JsonMap<String, Object> data = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(),JsonKeys.Key_Info);
                        isCollected = data.getBoolean("isCollected");
                        toast.showToast(data.getStringNoNull("msg"));
                    }
                }
            } else {
                //ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
            //relation_goods_xgv.stopLoadMore();
        }

    };


    private void setData(List<JsonMap<String, Object>> temp_data) {

        if (nPage == 0) {
            goodsDatas = temp_data;
            relationProductAdapter.setDatas(goodsDatas);
            //ptr_list.setAdapter(shoppingAdapter);
            relation_goods_xgv.setAdapter(relationProductAdapter);
            relationProductAdapter.notifyDataSetChanged();
        } else {
            goodsDatas.addAll(temp_data);
            relationProductAdapter.notifyDataSetChanged();
        }
        nPage++;
    }

    private void refreshGoodsDetail(JsonMap goodsDatas) {
        findDatas = goodsDatas;
        setCenter_title(goodsDatas.getStringNoNull("subTitle"));
        isCollected = goodsDatas.getBoolean("isCollected");
        boolean isHasMoreRelationPerson = goodsDatas.getBoolean("hasMoreRelatePerson",false);
        //setCommentsNum(commentsCounts);
        relationPersons = (ArrayList<JsonMap<String, Object>>) goodsDatas.getList_JsonMap("relationPersons");
//        for (int i=0;i<4;i++){
//            JsonMap<String,Object> jsonMap=new JsonMap<String, Object>();
//            jsonMap.put("userName","userName"+i);
//            relationPersons.add(jsonMap);
//        }
//        isHasMoreRelationPerson=true;

        if (relationPersons.size() != 0) {
            relation_person_layout.setVisibility(View.VISIBLE);
            for (int i = 0; i < relationPersons.size(); i++) {
                View relationView = getLayoutInflater().inflate(R.layout.relation_person_item, null);
                relationView.setLayoutParams(new LinearLayout.LayoutParams(MyApplication.getInstance().getScreenWidth() / relationPersons.size(), LinearLayout.LayoutParams.MATCH_PARENT));
                relationView.setTag(i);
                relationView.setOnClickListener(relationPersionClick);
                JsonMap jsonMap = relationPersons.get(i);
                TextView textView = (TextView) relationView.findViewById(R.id.userName_tv);
                CircleImageView user_photo_mask_iv = (CircleImageView) relationView.findViewById(R.id.user_photo_mask_iv);
                CircleImageView user_photo_iv = (CircleImageView) relationView.findViewById(R.id.user_photo_iv);
                textView.setText(jsonMap.getStringNoNull("userName"));
                ImageLoader.getInstance().displayImage(jsonMap.getStringNoNull("userIcon"), user_photo_iv, myApplication.getUserHeadOption());
                if (i == 4 && isHasMoreRelationPerson) {
                    user_photo_mask_iv.setVisibility(View.VISIBLE);
                    textView.setText(R.string.more);
                }
                relation_person_info.addView(relationView);
            }
        } else {
            relation_person_layout.setVisibility(View.GONE);
        }

        int relationGoodsNum = goodsDatas.getInt("relateGoodsCount", 0);
        if (relationGoodsNum > 0) {
            relation_goods_xgv.setVisibility(View.VISIBLE);
            relation_goods_title_layout.setVisibility(View.VISIBLE);
            relation_goods_xgv.setAdapter(relationProductAdapter);
            getRelationGoods();
        } else {
            relation_goods_xgv.setVisibility(View.GONE);
            relation_goods_title_layout.setVisibility(View.GONE);
        }
    }

    /**
     * 相关人员点击
     */
    View.OnClickListener relationPersionClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = (Integer) v.getTag();
            JsonMap jsonMap = relationPersons.get(id);
            String userId = jsonMap.getStringNoNull("userId");

            switch (id) {
                case 0:
                case 1:
                case 2:
                    scanUserBlog(userId);
                    break;
                case 3:
                    boolean isHasMoreRelationPerson = findDatas.getBoolean("hasMoreRelatePerson",false);

                    if (isHasMoreRelationPerson) {
                        Intent intent = new Intent(mContext, MoreRelationPersonActivity.class);
                        intent.putExtra(ExtraKeys.Key_Msg1, 1);
                        jumpTo(intent);
                    } else {
                        scanUserBlog(userId);
                    }
                    break;
                default:
            }

        }
    };

    private void setWebViewFeature() {
        WebSettings webSettings = find_contents_wb.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setEnableSmoothTransition(true);
        //webSettings.setBuiltInZoomControls(true);
        webSettings.setLightTouchEnabled(true);
        //webSettings.setSupportZoom(true);
        find_contents_wb.setHapticFeedbackEnabled(true);
        //register_agreement_wv.setWebViewClient(new MyWebUriViewClient());
        find_contents_wb.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    myProgressBar.setVisibility(View.INVISIBLE);
                    if (relationProductAdapter != null)
                        relationProductAdapter.notifyDataSetChanged();
                } else {
                    if (newProgress == 50) {
                        if (relationProductAdapter != null)
                            relationProductAdapter.notifyDataSetChanged();
                    }
                    if (View.VISIBLE != myProgressBar.getVisibility()) {
                        myProgressBar.setVisibility(View.VISIBLE);
                    }
                    myProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

        });
        webSettings.setUseWideViewPort(false);
        webSettings.setLoadWithOverviewMode(true);
    }


    /**
     * 分享
     */
    public void share_iv_click() {
        JsonMap jsonMap_temp = findDatas;
        String shareLogo = jsonMap_temp.getStringNoNull("sharePic");
        String shareTitle = jsonMap_temp.getStringNoNull("shareTitle");
        String shareContent = jsonMap_temp.getStringNoNull("shareSummary");
        if (TextUtils.isEmpty(shareContent)) {
            shareContent = jsonMap_temp.getStringNoNull("shareTitle");
        }
        String shareUrl = "FindBrand/FindBrandDetail?disId=" + discoredId;

        MyApplication.getInstance().showShareCompont(this, shareLogo, shareUrl, shareTitle, shareContent);
    }

    /**
     * 收藏文章
     */
    private void collect_tv_click() {
        if (Utils.isFastClick()) {
            return;
        }
        if(Utils.isHasLogin(mContext)) {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("userId", Utils.getUserId(this));
            params.put("articleID", discoredId);
            GetDataQueue queue = new GetDataQueue();
            queue.setActionName(GetDataConfing.Action_CollectionArtical);
            queue.setParamsNoJson(params);
            queue.setCallBack(callBack);
            queue.setWhat(GetDataConfing.What_CollectionArtical);
            getDataUtil.getData(queue);
        }else {
            gotoLogin();
        }
    }

    /**
     * 所有评论
     *
     * @param view
     */
    public void msg_iv_click(View view) {
//        if (TextUtils.isEmpty(comments) || comments.equalsIgnoreCase("0")) {
//            return;
//        }
        Intent intent = new Intent(this, ArticalCommentsActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, discoredId);
        intent.putExtra(ExtraKeys.Key_Msg2, findDatas.getStringNoNull("SubTitle"));
        jumpTo(intent, false);
    }


    /**
     * 所有评论
     *
     * @param view
     */
    public void more_iv_click(View view) {
        showPopWindowView();
    }


    public PopupWindow popupWindow;
    private TextView collect_tv;
    private TextView share_tv;
    private TextView cancel_tv;


    private void showPopWindowView() {
        if (popupWindow == null) {
            View view = getLayoutInflater().inflate(R.layout.artical_more_menu, null);
            popupWindow = new PopupWindow(view,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setContentView(view);
            popupWindow.setAnimationStyle(R.style.popupAnimation);
            collect_tv = (TextView) view.findViewById(R.id.collect_tv);
            share_tv = (TextView) view.findViewById(R.id.share_tv);
            cancel_tv = (TextView) view.findViewById(R.id.cancel_tv);
            if (isCollected) {
                collect_tv.setText(R.string.cancel_collection);
            }
            View select_v = view.findViewById(R.id.select_v);
            collect_tv.setOnClickListener(myclick);
            share_tv.setOnClickListener(myclick);
            select_v.setOnClickListener(myclick);
            cancel_tv.setOnClickListener(myclick);
            popupWindow.showAtLocation(tv_title, Gravity.NO_GRAVITY, 0, 0);

        } else if (!popupWindow.isShowing()) {
            popupWindow.showAtLocation(tv_title, Gravity.NO_GRAVITY, 0, 0);
        }
    }


    /**
     * “我的”点击事件
     */
    View.OnClickListener myclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = v.getId();
            popupWindow.dismiss();
            switch (id) {
                case R.id.share_tv:
                    share_iv_click();
                    break;
                case R.id.collect_tv:
                    collect_tv_click();
                    break;
                case R.id.select_v:
                    break;
                case R.id.cancel_tv:
                    //退出登录
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */

//        UMSocialService umSocialService=MyApplication.getInstance().getmController();
//        if(umSocialService!=null) {
//            UMSsoHandler ssoHandler =umSocialService.getConfig().getSsoHandler(requestCode);
//            if (ssoHandler != null) {
//                ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//            }
//        }

        UMSsoHandler ssoHandler = SocializeConfig.getSocializeConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

}